<template>
  <list-layout>
    <div slot="search">
      <el-form :model="queryParams" :inline="true" size="small" ref="queryForm" v-show="showSearch" label-width="88px">
        <el-row>
          <el-col :span="8">
            <!--            物料分类：-->
            <el-form-item :label="$t('formValidation.materialClassification')" prop="categoryIds">
              <el-cascader
                  :value="queryParams.categoryIds"
                  ref="cascader"
                  :options="data"
                  :props="{multiple: true, expandTrigger:'hover',emitPath:false,checkStrictly: true,value:'id',label:'label' }"
                  clearable
                  @change="cascaderChange"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--            所属基地：-->
            <el-form-item :label="$t('mrbForm.base')" prop="baseName">
              <!-- <el-input :disabled="isCanEdit" v-model="approvalModel.base" clearable size="small" /> -->
<!--              <el-select class="select-style" v-model="queryParams.baseId" clearable size="small" placeholder="请选择">-->
<!--                <el-option-->
<!--                    v-for="item in baseoption"-->
<!--                    :key="item.baseName"-->
<!--                    :label="item.baseName"-->
<!--                    :value="item.baseId">-->
<!--                </el-option>-->
<!--              </el-select>-->
              <base-dialog v-model="queryParams.baseName" @callback="(row)=>queryParams.baseId=row.baseId"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--            所属厂区：-->
            <el-form-item :label="$t('formValidation.affiliatedFactoryArea')" prop="factoryCode">
              <!-- <el-input :disabled="isCanEdit" v-model="approvalModel.base" clearable size="small" /> -->
              <!--              <el-select class="select-style" v-model="queryParams.factoryCode" clearable size="small"-->
              <!--                         placeholder="请选择">-->
              <!--                <el-option-->
              <!--                    v-for="item in factoryList"-->
              <!--                    :key="item.plantCode"-->
              <!--                    :label="item.plantName"-->
              <!--                    :value="item.plantCode">-->
              <!--                </el-option>-->
              <!--              </el-select>-->
              <FactoryDialog v-model="queryParams.factoryName"
                             @callback="(row)=>queryParams.factoryCode = row.plantCode" :clearable="false"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <!--            检验日期：-->
            <el-form-item :label="$t('bommaterial.inspectDate')" prop="createTime">
              <el-date-picker v-model="dateRange" size="small" value-format="yyyy-MM-dd" type="daterange"
                              autocomplete="off" range-separator="-" :start-placeholder="$t('public.startDate')"
                              :end-placeholder="$t('public.endDate')"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--            样本编号：-->
            <el-form-item :label="$t('specimen.sampleCode')" prop="sampleCode">
              <el-input v-model="queryParams.sampleCode"
                            :placeholder="$t('public.placeholder', { placeholder: $t('specimen.sampleCode') })" clearable
                            size="small"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <!--            样本编号：-->
            <el-form-item label="检验批编号" prop="sampleCode">
              <el-input v-model="queryParams.inspectionLotMark"
                            :placeholder="$t('public.placeholder', { placeholder: '检验批编号' })" clearable
                            size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--            样本编号：-->
            <el-form-item label="物料编号" prop="sampleCode">
              <el-input v-model="queryParams.materialCode"
                            :placeholder="$t('public.placeholder', { placeholder: '物料编号' })" clearable
                            size="small"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col align="center">

            <el-form-item class="right-btns">
              <!--              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">-->
              <!--                {{ $t('public.search') }}-->
              <!--              </el-button>-->
              <el-button type="primary" icon="el-icon-s-data" size="mini" @click="generateTable">
                {{ $t('formValidation.generateResume') }}
              </el-button>
              <el-button icon="el-icon-refresh" class="resectBtn" size="mini" @click="resetQuery">
                {{ $t('public.reset') }}
              </el-button>
              <el-button icon="el-icon-printer" class="exportitemBtn" size="mini" @click="handleExport"
                         v-hasPermi="['ny-iqc:ncrReview:export']">
                {{ $t('inventoryManagement.generateResumeFile') }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

    </div>
    <div class="app-container">
      <div class="container-table">
        <el-table :height="tableHeight" border v-loading="loading" :data="typeList">

          <!--          序号-->
          <el-table-column :label="$t('public.serialNum')" type="index" width="55" align="center"/>

          <!--          所属基地-->
          <el-table-column :label="$t('mrbForm.base')" align="left" prop="baseName" minWidth="160"
                           show-overflow-tooltip/>

          <!--          所属厂区-->
          <el-table-column :label="$t('formValidation.affiliatedFactoryArea')" align="left" prop="factoryName" minWidth="160"
                           show-overflow-tooltip/>

          <!--          月份-->
          <!--          <el-table-column label="月份" align="left" prop="materialCode" minWidth="160"-->
          <!--                           show-overflow-tooltip/>-->
          <!--          供应商名称-->
          <el-table-column :label="$t('basicData.supplierName')" align="left" prop="supplierName" minWidth="160"
                           show-overflow-tooltip/>
          <!--          到货日期-->
          <el-table-column :label="$t('inspectionManagement.cputime')" align="left" prop="cputime" minWidth="160"
                           show-overflow-tooltip/>
          <!--          检验日期-->
          <el-table-column :label="$t('bommaterial.inspectDate')" align="left" prop="inspectionStartTime" minWidth="160"
                           show-overflow-tooltip/>
          <!--          物料种类-->
          <el-table-column :label="$t('formValidation.materialType')" align="left" prop="materialType" minWidth="160"
                           show-overflow-tooltip/>
          <!--          物料名称-->
          <el-table-column :label="$t('mrbForm.materialName')" align="left" prop="materialName" minWidth="160"
                           show-overflow-tooltip/>
          <!--          批次号-->
          <el-table-column :label="$t('bommaterial.batchNo')" align="left" prop="inspectionLotMark" minWidth="160"
                           show-overflow-tooltip/>
          <!--          物料编码-->
          <el-table-column :label="$t('material.materialCode')" align="left" prop="materialCode" minWidth="160"
                           show-overflow-tooltip/>
          <!--          规格型号-->
          <el-table-column :label="$t('inspectionManagement.measuringModel')" align="left" prop="specificationsModels"
                           minWidth="160"
                           show-overflow-tooltip/>
          <!--          物料属性-->
          <el-table-column :label="$t('formValidation.materialProperties')" align="left" prop="materialProperties" minWidth="160"
                           show-overflow-tooltip/>
          <!--          进料总数-->
          <el-table-column :label="$t('formValidation.totalNumberOfFeeds')" align="left" prop="batchAmount" minWidth="160"
                           show-overflow-tooltip/>
          <!--          单位-->
          <el-table-column :label="$t('mrbForm.unit')" align="left" prop="mengeneinh" minWidth="160"
                           show-overflow-tooltip/>
          <!--          检验结果-->
          <el-table-column :label="$t('defectIncoming.inspectResults')" align="left" prop="result" minWidth="160"
                           show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ result(scope.row) }}</span>
            </template>
          </el-table-column>
          <!--          处置方式-->
          <el-table-column :label="$t('formValidation.disposalMethod')" align="left" prop="usingDecision" minWidth="160"
                           show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ formatCE_NCR(scope.row) }}</span>
            </template>
          </el-table-column>
          <!--          入库数量-->
          <el-table-column :label="$t('formValidation.inboundQuantity')" align="left" prop="accountAmount" min-width="100"
                           :show-overflow-tooltip="true"/>
          <!--          检验员-->
          <el-table-column :label="$t('inventoryManagement.inspector')" align="left" prop="inspectorName" minWidth="160"
                           show-overflow-tooltip/>
          <!--          检验项-->
          <el-table-column :label="$t('inventoryManagement.checkItem')" align="left" prop="projectName" minWidth="160"
                           show-overflow-tooltip/>
          <!--          样本编号-->
          <el-table-column :label="$t('specimen.sampleCode')" align="left" prop="sampleCode" minWidth="160"
                           show-overflow-tooltip/>
          <!--          检验值1-->
          <el-table-column :label="$t('inventoryManagement.inspectionValue')+'1'" align="left" prop="checkoutResult1"
                           minWidth="160"
                           show-overflow-tooltip/>
          <!--          检验值2-->
          <el-table-column :label="$t('inventoryManagement.inspectionValue')+'2'" align="left" prop="checkoutResult2"
                           minWidth="160"
                           show-overflow-tooltip/>
          <!--          检验值3-->
          <el-table-column :label="$t('inventoryManagement.inspectionValue')+'3'" align="left" prop="checkoutResult3"
                           minWidth="160"
                           show-overflow-tooltip/>
          <!--          检验值4-->
          <el-table-column :label="$t('inventoryManagement.inspectionValue')+'4'" align="left" prop="checkoutResult4"
                           minWidth="160"
                           show-overflow-tooltip/>
          <!--          检验值5-->
          <el-table-column :label="$t('inventoryManagement.inspectionValue')+'5'" align="left" prop="checkoutResult5"
                           minWidth="160"
                           show-overflow-tooltip/>
          <!--          检验值6-->
          <el-table-column :label="$t('inventoryManagement.inspectionValue')+'6'" align="left" prop="checkoutResult6"
                           minWidth="160"
                           show-overflow-tooltip/>
          <!--          检验值7-->
          <el-table-column :label="$t('inventoryManagement.inspectionValue')+'7'" align="left" prop="checkoutResult7"
                           minWidth="160"
                           show-overflow-tooltip/>
          <!--          检验值8-->
          <el-table-column :label="$t('inventoryManagement.inspectionValue')+'8'" align="left" prop="checkoutResult8"
                           minWidth="160"
                           show-overflow-tooltip/>
          <!--          检验值9-->
          <el-table-column :label="$t('inventoryManagement.inspectionValue')+'9'" align="left" prop="checkoutResult9"
                           minWidth="160"
                           show-overflow-tooltip/>
          <!--          检验值10-->
          <el-table-column :label="$t('inventoryManagement.inspectionValue')+'10'" align="left" prop="checkoutResult10"
                           minWidth="160"
                           show-overflow-tooltip/>
          <!--          <el-table-column :label="$t('mrbForm.useDecision')" align="left" prop="usingDecision" minWidth="160"-->
          <!--                           show-overflow-tooltip>-->
          <!--            <template slot-scope="scope">-->
          <!--              <span>{{ usingDecisionFilter(scope.row) }}</span>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                    @pagination="generateTable" layout="total, sizes, prev, pager, next, jumper"/>
      </div>
    </div>
  </list-layout>
</template>

<script>
import {
  getIncomingMaterialHistoryList
} from '@/api/basic/materialClassification'
import {mapGetters, mapState} from 'vuex'
import {getTree, exportExcel, generate} from '@/api/basic/materialClassification'
import {baseList} from '@/api/masterdata/base'
import {listAllFactory} from '@/api/basic/factory'
import FactoryDialog from '@/views/components/FactoryDialog'
import BaseDialog from '@/views/components/BaseDialog'


//基础数据-物料信息管理
export default {
  name: 'MRBList',
  dicts: ['NYIQC_NCR_DECISION'],
  components: {
    FactoryDialog,
    BaseDialog
  },
  computed: {
    ...mapGetters(['userId', 'name', 'deptName']),
    ...mapState({
      isFold: (state) => state.app.isFold,
    }),
  },
  data() {
    const data = []
    return {
      factoryList: [],
      baseoption: [],
      data: JSON.parse(JSON.stringify(data)),
      dialogType: 1, //1:新增  2：编辑 3：查看
      dialogForm: {
        lotUse: '',
      },
      processCode: '0',
      operateType: 'add',
      lastStep: false,
      deviceOptions: [],
      factoryOptions: [],
      approvalOpen: false,
      tableHeight: 'calc(100vh - 308px)',
      direction: 'rtl',
      addInspection: false,
      visible: false,
      visibleRectify: false,
      drawer: false,
      viewModel: {
        inspectionInformation: '0',
      },
      editModel: {
        inspectionInformation: '0',
      },
      approvalForm: {
        status: '1',
        textarea: '',
      },
      selBtn: 1,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      userlist: [],
      // 弹出层标题
      title: '发起MRB',
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],

      // 查询参数
      queryParams: {
        baseId: '',
        categoryIds: [],
        factoryCode: '',
        inspectionEndTime: '',
        inspectionStartTime: '',
        sampleCode:'',
        pageNum:1,
        pageSize:20
      },
      // 表单参数
      form: undefined,

      fullscreen: false,
      isShowApprovalDialog: false,
      auditForm: {
        status: null,
        reviewFile: '',
        planRemark: ''
      },
      // 表单校验
      auditRules: {
        status: [
          {
            required: true,
            message: '状态不能为空',
            trigger: 'change',
          },
        ],
        reviewFile: [
          {
            required: true,
            message: '附件不能为空',
            trigger: 'change',
          },
        ],
        planRemark: [
          {
            required: true,
            message: '备注不能为空',
            trigger: 'blur',
          },
        ],
      },
      fileId: '',
      unPassStageList: [],
      annexFileList: [],
      ncrStatus: '' // ncr状态
    }
  },
  mounted() {
    if (this.$route.query.status) {
      this.queryParams.usingDecision = this.$route.query.status
    }
    if (this.$route.query.uniqueId) {
      this.queryParams.id = this.$route.query.uniqueId
    }
    this.getTreeList()
    baseList({pageSize: 1000}).then(res => {
      this.baseoption = res.rows
    })
    listAllFactory().then((res) => {
      this.factoryList = res.data
    })
  },
  methods: {
    cdsss(children){
      for (const iterator of children) {
        if(this.queryParams.categoryIds.indexOf(iterator.value) == -1){
          this.queryParams.categoryIds.push(iterator.value)
        }
        this.cdsss(iterator.children)
      }
      // 结束时保存选中节点
      this.queryParams.categoryIds = [...this.queryParams.categoryIds]
      this.$forceUpdate()
    },
    cdxDeep(id,children){
      for (const iterator of children) {
        let index = this.queryParams.categoryIds.indexOf(iterator.id)
          index != -1 ? this.queryParams.categoryIds.splice(index,1) : ''
          this.cdxDeep(id,iterator.children ? iterator.children : [])
      }
    },
    cdxxx(id,children){
      for (const iterator of children) {
        if(id == 'deep'){
          let index = this.queryParams.categoryIds.indexOf(iterator.id)
          index != -1 ? this.queryParams.categoryIds.splice(index,1) : ''
          this.cdxDeep('deep',iterator.children ? iterator.children : [])
        }
        if(iterator.id == id){
          let index = this.queryParams.categoryIds.indexOf(iterator.id)
          index != -1 ? this.queryParams.categoryIds.splice(index,1) : ''
          this.cdxDeep('deep',iterator.children ? iterator.children : [])
          return
        }else{
          this.cdxxx(id,iterator.children ? iterator.children : [])
        }
      }
    },
    cascaderChange(children){
      console.log(children,this.queryParams.categoryIds)
      let queryParamsCategoryIds = [...this.queryParams.categoryIds]
      if(children.length <= this.queryParams.categoryIds.length){
        let deleteCaId = null
        for (const id of this.queryParams.categoryIds) {
          if(children.indexOf(id) == -1){
            deleteCaId = id
            break;
          }
        }
        console.log('删除操作')
        this.cdxxx(deleteCaId,this.data)
      }else{
        console.log('新增操作')
        // this.queryParams.categoryIds = []
        console.log(this.$refs['cascader'].getCheckedNodes())
        let children = this.$refs['cascader'].getCheckedNodes()
        console.log(children)
        console.log(this.queryParams.categoryIds)
        children = children.filter(val => queryParamsCategoryIds.indexOf(val.value) == -1)
        console.log(children,'传送的NODE项')
        this.cdsss(children)
      }
      console.log(children,'重置前的操作')
      if(children.length == 0){
        console.log('我进来了')
        this.$refs['cascader'].$data.checkedValue = {}
      }else{
        this.$refs['cascader'].$data.checkedValue = [...this.queryParams.categoryIds]
      } 
      console.log(this.$refs['cascader'])
    },
    cascaderDeep(children){
      for (const iterator of children) {
        this.queryParams.categoryIds.push(iterator.id)
        if(iterator.children&&iterator.children.length){
          this.cascaderDeep(iterator.children)
        }else{
          return
        }
      }
    },
    formatCE_NCR(e) {
      if (e) {
        return this.dict.label.NYIQC_NCR_DECISION[e.usingDecision];
      } else {
        return ''
      }
    },
    result(data) {
      if (data.result == '1') {
        return '合格'
      }
      if (data.result == '0') {
        return '不合格'
      }
    },
    getTreeList() {
      getTree().then((response) => {
        this.data = response.data
      })
    },
    handleExport() {
      let dateRange = this.dateRange;
      this.queryParams.inspectionStartTime = dateRange[0]
      this.queryParams.inspectionEndTime = dateRange[1]
      // this.otherDownload(
      //     '/ny-iqc/resume/export',
      //     this.queryParams,
      //     `type_${new Date().getTime()}.xlsx`,
      // )
      //exportExcel
      exportExcel(this.queryParams).then((response) => {
        if (response.code==200){
          this.$modal.msgSuccess(response.data)
        }
      })
    },
    /** 搜索按钮操作 */
    // handleQuery() {
    //   this.queryParams.pageNum = 1
    //   let dateRange = this.dateRange;
    //   this.queryParams.inspectionStartTime = dateRange[0]
    //   this.queryParams.inspectionEndTime = dateRange[1]
    //   this.getList()
    // },
    generateTable() {
      let dateRange = this.dateRange;
      this.queryParams.inspectionStartTime = dateRange[0]
      this.queryParams.inspectionEndTime = dateRange[1]
      this.loading = true
      generate(this.queryParams).then((response) => {
        if (response.code == 200 && response.rows) {
          this.typeList = response.rows
          this.total = response.total
          this.tableHeight = this.isFold
              ? 'calc(100vh - 308px)'
              : 'calc(100vh - 466px)'
          this.loading = false
        }
      }).catch(error => {
        // 处理请求失败的错误信息
        this.loading = false
      });
    },
    /** 重置按钮操作 */
    resetQuery() {

      this.queryParams={
         ...this.queryForm,
        baseId: '',
        categoryIds: [],
        factoryCode: '',
        inspectionEndTime: '',
        inspectionStartTime: '',
        sampleCode:'',
        pageNum:1,
        pageSize:20
      }

      // pageNum:1,
      // pageSize:20
    },
  },
}
</script>
<style lang="scss" scoped>
.file-upload-box {
  line-height: 20px;
}

::v-deep .el-form-item__content {
  line-height: 32px;
}

::v-deep .el-upload__tip {
  line-height: 20px;
}

::v-deep .el-card {
  // padding-top: 20px;
  border: 0px;
  box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
  border-radius: 4px;
  padding-bottom: 20px;
}

::v-deep .el-aside {
  padding: 0;
  margin-bottom: 0;
}

.content-style {
  border: 0px;
  box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
  border-radius: 2px;
  background-color: white;
  margin-top: 10px;
}

::v-deep .el-button-group .selBtn {
  background: #fff;
  border: 1px solid #0b7be3;
  color: #0b7be3;
}

::v-deep .el-button-group .unselBtn {
  background: #fff;
  border: 1px solid #ededf2;
  color: #666666;
}

.header-left {
  font-size: 14px;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #333333;
  padding: 3px 0 10px;
  display: inline-flex;
  justify-content: center;
  border-bottom: 2px solid #0b7be3;
}

.header-right {
  float: right;
}

.container-header {
  border-bottom: 1px solid #ededf2;
}

.container-table {
  float: left;
  //margin-top:6px;
  width: 100%;
}

.mb8 {
  float: left;
  margin-top: 6px;
  width: 100%;
}

.drawer-footer {
  display: flex;
  position: relative;
  z-index: 9999;
  bottom: -40px;
  height: 40px;
  justify-content: center;
  width: 100%;
}

.drawer-close {
  background: #f7f8fa;
  border-color: #f7f8fa;
}

.right-btns ::v-deep .el-button {
  margin-top: 0;
}

.app-container {
  padding: 0;
}

.table-action-wrap {
  padding: 12px 0;
}

::v-deep .rowHighLight {
  background: oldlace;
}

::v-deep .el-dialog__body {
  max-height: 500px;
  overflow-y: auto;
}

.select-style {
  width: 100%;
}
</style>
